import os,string,urllib2,urllib
import musicbrainz2.webservice as ws
import musicbrainz2.wsxml as xml
import musicbrainz2.model as mdl
import pylast
API_Key="59a5d7fa32f755407c332cb79e4ddbf4"
secret="f6820c1d8e4f0e6d6d69ea7ec4a01578"
genre=list()
genre.append([u"blues"])
genre.append([u"classic rock",u"classic-rock"])
genre.append([u"progressive rock",u"progressiverock",u"progressive-rock"])
genre.append([u"country"])
genre.append([u"dance",u"eurodance"])
genre.append([u"accoustic"])
genre.append([u"funk"])
genre.append([u"grunge"])
genre.append([u"hip hop",u"hip-hop",u"hiphop"])
genre.append([u"jazz",u"acid jazz"])
genre.append([u"metal",u"death metal",u"nu metal",u"power metal",u"speed metal"])
genre.append([u"new age",u"new-age"])
genre.append([u"oldies"])
genre.append([u"pop"])
genre.append([u"r&b",u"rnb"])
genre.append([u"rap"])
genre.append([u"reggae"])
genre.append([u"rock"])
genre.append([u"techno",u"euro techno",u"euro - techno"])
genre.append([u"industrial"])
genre.append([u"alternative"])
genre.append([u"ska"])
genre.append([u"biesiada"])
genre.append([u"soundtrack",u"movie soundtrack",u"movie-soundtrack"])
genre.append([u"ambient"])
genre.append([u"trip-hop"])
genre.append([u"vocal"])
genre.append([u"electro",u"electro house"])
genre.append([u"fusion"])
genre.append([u"trance"])
genre.append([u"classical",u"classic"])
genre.append([u"instrumental"])
genre.append([u"acid"])
genre.append([u"house"])
genre.append([u"game"])
genre.append([u"sound clip"])
genre.append([u"gospel"])
genre.append([u"noise"])
genre.append([u"alternative",u"alternrock",u"alternative Rock",u"alternative-rock",u"alternativerock"])
genre.append([u"bass",u"drumnbase",u"drumandbase",u"drum and base"])
genre.append([u"soul"])
genre.append([u"punk",u"punk rock"])
genre.append([u"space"])
genre.append([u"pop-punk",u"pop punk"])
genre.append([u"instrumental pop"])
genre.append([u"instrumental rock"])
genre.append([u"ethnic"])
genre.append([u"gothic"])
genre.append([u"hardcore"])
genre.append([u"techno-industrial"])
genre.append([u"electronic"])
genre.append([u"folk",u"pop-folk"])
genre.append([u"dream"])
genre.append([u"southern rock"])
genre.append([u"comedy"])
genre.append([u"cult"])
genre.append([u"gangsta"])
genre.append([u"party music",u"top 40"])
genre.append([u"christian rap"])
genre.append([u"pop/funk"])
genre.append([u"jungle"])
genre.append([u"native american"])
genre.append([u"accoustic"])
genre.append([u"new wave"])
genre.append([u"psychadelic"])
genre.append([u"rave"])
genre.append([u"showtunes"])
genre.append([u"trailer"])
genre.append([u"emo"])
genre.append([u"tribal"])
genre.append([u"acid punk"])
genre.append([u"indie",u"indie rock"])
genre.append([u"retro"])
genre.append([u"musical"])
genre.append([u"rock & roll",u"rocknroll",u"rock&roll"])
genre.append([u"hard rock",u"hardrock"])#############################worker##################################

class airborne:
# a forward iterator that traverses a directory tree
    def __init__(self, directory):
        self.stack = [directory]
        self.files = []
        self.index = 0

    def __getitem__(self, index):
        while 1:
            try:
                file = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack
                self.directory = self.stack.pop()
                try:
                    self.files = os.listdir(self.directory)
                    self.index = 0
                except: continue
            else:
                # got a filename
                fullname = os.path.join(self.directory, file)
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    self.stack.append(fullname)
                else:
                    return fullname
def makeid3(liste,desperate=0):
    final=list()
    for item in liste:
            for j in range(len(genre)):					#Durchsuchen der Genre Liste nach passendem Genre
                    if item.lower() in genre[j]:
                                    tempstring=string.capwords(genre[j][0])		#Kapitalization des genres
                                    if tempstring not in final:
                                            final.append(tempstring)
            if(desperate==1):
                    if (final!=[]):break
    finalstring=""
    for item in final[:2]:
            finalstring=finalstring+item+"\0"
    return finalstring
def filename(clas):
    if "artist" in str(type(clas)):
        n="artist"
    elif "album" in str(type(clas)):
        n="album"
    elif "genre" in str(type(clas)):
        n="genre"
    return n
def lm_picture(artist,album):
    import pylast
    username = "Arpheno"
    password_hash = pylast.md5("9.1g2-")

    network = pylast.get_lastfm_network(api_key = API_Key, api_secret = 
        secret, username = username, password_hash = password_hash)

    album=network.get_album(artist, album)
    return urllib2.urlopen(album.get_cover_image(4)).read()
def mb_album(artist,title):
    q=ws.Query()
    t_filter=ws.TrackFilter(artistName=unicode(su(artist)),title=unicode(su(title)))
    t_result=q.getTracks(t_filter)
    t_track=t_result[0].getTrack()
    return t_track.getReleases()[0].getTitle()


def kickparentheses(passed):
                passed=passed.lower()
                if("(" in passed):
                        passed=passed[:passed.find("(")]
                if("[" in passed):
                        passed=passed[:passed.find("[")]
                return passed
def kickfeat(passed):
                passed2=passed.lower()
                if("ft." in passed2):
                   passed=passed[:passed2.find("ft.")]     
		if(" ft" in passed2):						##C# Modify Tags containting "Featuring" or such
		   passed=passed[:passed2.find(" ft")]			#
		if(" feat" in passed2):									#
		   passed=passed[:passed2.find(" feat")]
		if("," in passed2):									#
		   passed=passed[:passed2.find(",")]
		if("f." in passed2):									#
		   passed=passed[:passed2.find("f.")]
		if(" vs" in passed2):									#
		   passed=passed[:passed2.find(" vs")]
                if(" v." in passed2):									#
		   passed=passed[:passed2.find(" v.")]
		if(" + " in passed2):									#
		   passed=passed[:passed2.find(" + ")]
		if("feat" in passed2)and ("defeat" not in passed2):	#
		   passed=passed[:passed2.find("feat")]
		passed=passed.rstrip()
		return passed

def getfield(fname,query,pointsto=0):
                first=query.find("<"+fname+">",pointsto)+len(fname)+2
		firstwordofname=""
		for letter in fname:
			if(letter==" "):
				break
			
			firstwordofname=firstwordofname+letter
		second=query.find("</"+firstwordofname+">",first)
		if (first==-1 or second==-1):
                        return ""
		return (query[first:second],second)

def su(item):
    if type(item)==unicode:
        item=item.encode('utf-8')
    return item               
def sort_file(name):
    with open(name,'r') as f:
        content=f.readlines()
        content=sorted(content)
    with open(name,'w') as f:
        pass
    with open(name,'a') as f:
        for item in content:
            f.write(item)

